package com.xianggu.lock.demo;

import com.xianggu.lock.Lock;
import com.xianggu.lock.XiangGuLock;
import com.xianggu.lock.XiangGuReentryLock;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {
//    private final ReentrantLock lock = new ReentrantLock();
    private final Lock lock = new XiangGuReentryLock();

    private int state = 10;
    private int count = 10;

    // 方法1：获取锁后调用方法2
    public void method1() {
        lock.lock();
        try {
            state--;
            System.out.println(Thread.currentThread().getName() + " 进入 method1 当前state:" + state);
            method2(); // 在锁内调用方法2
        } finally {
            lock.unlock();
        }
    }

    // 方法2：同样需要获取锁
    public void method2() {
        lock.lock();
        try {
            count--;
            System.out.println(Thread.currentThread().getName() + " 进入 method2 当前count:" + count);
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo demo = new ReentrantLockDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> demo.method1(), "线程：" + i).start();
        }
    }
}